from ac import models
from PIL import Image
from django.conf import settings
import os


class Tree(object):
    """
    接收一个根节点的ID值，然后递归检查是否挂载用户，有则抛出异常；之后并把所有子孙节点的组织属性修改为失效状态
    """
    def __init__(self, pk):
        # self.handle(models.Org.objects.filter(pk=pk)[0])
        self.pk = pk
        # self.list_query = models.Org.objects.none()
        self.list_query = []

    def get_child(self, id):
        return models.Org.objects.filter(parent_id=id)

    def handle(self, query, max_org=False):
        if not query.is_active:         # 如果状态已经是False的则不需要继续处理了
            return
        assert not models.UserOrgMap.objects.filter(org=query), (       # 如果有用户挂载则抛出异常
            "組織節點‘%s’中仍有用戶存在!" % query.org_name
        )

        self.list_query.append(query)       # 累积待删除的列
        # query.is_active = False
        # query.save(force_update=True, update_fields=('is_active', ), max_org=max_org)
        return

    def parse(self):
        queryset = self.get_child(self.pk)
        for query in queryset.iterator():
            self.handle(query)
            self.pk = query.pk
            self.parse()
        return


def user_parser(obj):
    # data = []
    # for obj in args:
    #     data.append(
    #         {
    #             'username': obj.username, 'english_name': obj.first_name, 'chinese_name': obj.last_login,
    #             'org': obj.get_org_str(), 'site': obj.site.site_name, 'email': obj.email, 'sex': obj.sex,
    #             'create_date': obj.date_joined, 'duty': obj.duty.name, 'short_number': obj.short_number,
    #             'mobile_phone': obj.mobile_phone, 'ext': obj.ext, 'head': obj.head, 'sign': obj.sign,
    #             'last_login': obj.last_login, 'entry_date': obj.entry_date
    #         }
    #     )
    return {
                'username': obj.username, 'english_name': obj.first_name, 'chinese_name': obj.last_name,
                'org': obj.get_org_str(), 'site': obj.site.site_name, 'email': obj.email, 'sex': obj.sex,
                'create_date': obj.date_joined.strftime(settings.REST_FRAMEWORK["DATETIME_FORMAT"]),
                'duty': obj.duty.__str__(), 'short_number': obj.short_number,
                'mobile_phone': obj.mobile_phone, 'ext': obj.ext, 'head': obj.head, 'sign': obj.sign,
                'last_login': obj.last_login.strftime(settings.REST_FRAMEWORK["DATETIME_FORMAT"]),
                'entry_date': obj.entry_date, 'id': obj.pk, 'motto': obj.motto
            }


def handle_image(img, file_name, save_path, url_path):
    """
    保存一张图片文件至本地的方法，可以添加处理操作
    :param img:
    :param file_name:
    :param save_path:
    :param url_path:
    :return:
    """

    first, last = img.name.split(".")
    last = last.lower()
    # print(img.name, 222)
    # 大頭像處理及保存在指定地址
    full_name = file_name + "." + last
    # print(full_name, 333)
    file_path = save_path + full_name
    # print(file_path, 444)
    if os.path.exists(file_path):  # 去除舊數據
        os.remove(file_path)
    image = Image.open(img)
    # image.thumbnail((300, 300))   # 裁剪照片
    save_path = save_path + full_name
    image.save(save_path)
    image.close()
    url_path = url_path + full_name
    return url_path



